package cn.zooz.common.util.kit;

import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.util.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

/**
 * Created by Bradish7Y on 2017/3/17.
 */
public class KaptchaServlet extends HttpServlet implements Servlet {
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    private Properties props = new Properties();
    private Producer kaptchaProducer = null;

    @Override
    public void init(ServletConfig conf) throws ServletException {
        super.init(conf);
        ImageIO.setUseCache(false);
        Enumeration<?> initParams = conf.getInitParameterNames();
        while (initParams.hasMoreElements()) {
            String key = (String) initParams.nextElement();
            String value = conf.getInitParameter(key);
            this.props.put(key, value);
        }
        Config config = new Config(this.props);
        this.kaptchaProducer = config.getProducerImpl();
    }

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            resp.setDateHeader("Expires", 0);
            resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            resp.addHeader("Cache-Control", "post-check=0, pre-check=0");
            resp.setHeader("Pragma", "no-cache");
            resp.setContentType("image/jpeg");
            String capText = this.kaptchaProducer.createText();
            String key = WebUtils.getCookie(req, "test");
            if (key != null) {
                /**先清理缓存老数据**/
                //RedisUtil.delValue(key);
                /**存放缓存新数据**/
                //RedisUtil.setMapValue(key, com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, capText);
            }
            BufferedImage bi = this.kaptchaProducer.createImage(capText);
            ServletOutputStream out = resp.getOutputStream();
            ImageIO.write(bi, "jpg", out);
        } catch (Exception e) {
            logger.error("获取验证码信息失败:系统异常 ", e);
        }
    }

}
